from func_timeout import func_set_timeout
from pdf2docx import Converter
import os
import subprocess


@func_set_timeout(800)
def pdf_docx(pdf_path: str):
    # docx文件名称
    docx_name = pdf_path.split('.')[0] + '.docx'
    cv = Converter(pdf_path)
    cv.convert(docx_name)
    cv.close()
    return docx_name


def doc_convert_docx(file_path, outdir):
    # doc转docx
    subprocess.run(['soffice', '--headless', '--convert-to', 'docx', '--outdir', outdir, file_path])
    return outdir


@func_set_timeout(240)
def thread_to_docx(file_path):
    # linux 下doc转docx
    index_start = file_path.rindex(os.sep)
    index_end = file_path.rindex('.')
    file_name = file_path[index_start + 1:index_end]
    outdir = file_path[:index_start]
    doc_convert_docx(file_path, outdir)
    # 获取新文件路径
    file_paths = outdir + os.sep + file_name + '.docx'
    return file_paths


def doc_error():
    subprocess.run('pkill soffice', shell=True)


def pdf_convert_docx_service(pdf_path: str):
    if not os.path.exists(pdf_path):
        return {"code": 500, "message": "文件不存在"}

    try:
        docx_path = pdf_docx(pdf_path)
        return {"code": 200, "docx_path": docx_path, "message": "文件转换成功"}
    except:
        return {"code": 500, "message": "文件转换失败，转换超时"}


def doc_convert_docx_service(doc_path: str):
    if not os.path.exists(doc_path):
        return {"code": 500, "message": "文件不存在"}

    try:
        docx_path = thread_to_docx(doc_path)
        return {"code": 200, "docx_path": docx_path, "message": "文件转换成功"}
    except:
        doc_error()
        return {"code": 500, "message": "文件转换失败，转换超时"}


def to_docx(file_path):
    if file_path.file_path.endswith('.pdf') or file_path.file_path.endswith('.PDF'):
        return pdf_convert_docx_service(file_path.file_path)
    elif file_path.file_path.endswith('.doc') or file_path.file_path.endswith('.DOC'):
        return doc_convert_docx_service(file_path.file_path)
    else:
        return {"code": 500, "message": "只支持pdf、doc类型的文件转换"}


def to_html(file_path):
    if not os.path.exists(file_path.file_path):
        return {"code": 500, "message": "文件不存在"}
    htm_path = file_path.file_path.split('.')[0] + '.htm'
    outdir = file_path.file_path[:file_path.file_path.rindex(os.sep)] + os.sep
    subprocess.run(['soffice', '--headless', '--convert-to', 'htm', '--outdir', outdir, file_path.file_path])
    if os.path.exists(htm_path):
        return {"code": 200, "htm_path": htm_path, "message": "文件转换成功"}
    else:
        return {"code": 500, "message": "文件转换失败，转换超时"}

